﻿using AuthCenter.Api.Write.Application.Command.Role;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using AutoMapper;
using MediatR;
using System.Transactions;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace AuthCenter.Api.Write.Application.Hander.Role
{
    public class AddUserModelHander : IRequestHandler<AddUserModelCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> _roleRepository;
        private readonly IBaseRepository<UserRoleModel> _userRoleRepository;
        private readonly IBaseRepository<UserModel> _userRepository;
        private readonly IMapper _mapper;
        public AddUserModelHander(IBaseRepository<RoleModel> roleRepository, IMapper mapper, IBaseRepository<UserRoleModel> userRoleRepository, IBaseRepository<UserModel> userRepository)
        {
            _roleRepository = roleRepository;
            _mapper = mapper;
            _userRoleRepository = userRoleRepository;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 添加用户角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(AddUserModelCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {


                var list = new List<UserRoleModel>();
                foreach (var item in request.UserId)
                {
                    list.Add(new UserRoleModel
                    {
                        UserId = item,
                        RoleId = request.RoleId
                    });
                }
                int i=_userRoleRepository.Create(list);

                tran.Complete();
                if (i > 0)
                {
                    res.Code = ApiEnums.OK;
                    res.Message = "分配成功";
                    res.Data = i;
                }
                else 
                {
                    res.Code = ApiEnums.Fail;
                    res.Message = "分配失败";
                }
                return Task.FromResult(res);
            }
        }
    }
}
